﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Web.Security;
using NTQOnlineExam.Services.DBCommand.Account;
using NTQOnlineExam.Services.EntityFW.Context;
using NTQOnlineExam.Services.EntityFW.Entity;
using NTQOnlineExam.Services.EntityFW.Repository;
using NTQOnlineExam.Services.Infrastructure;
using NTQOnlineExam.Services.Models;
using AutoMapper.Mappers;

namespace NTQOnlineExam.Services.ReportService.Account
{
    public class AccountReportService : IAccountReportService
    {
        private readonly ICommandExecutor _executor;
        private readonly EntityFW.Repository.IGenericRepository<UserProfile> _userRepository;


        public AccountReportService(ICommandExecutor executor, IGenericRepository<UserProfile> userRepository)
        {
            _executor = executor;
            _userRepository = userRepository;
        }

        public UserProfileDTO GetByUserName(string userName)
        {
            var userProfile =_userRepository.Get(u => string.Compare(u.UserName, userName, StringComparison.InvariantCultureIgnoreCase) == 0).FirstOrDefault();
            return AutoMapper.Mapper.Map<EntityFW.Entity.UserProfile, UserProfileDTO>(userProfile);
        }

        public IList<UserProfileDTO> GetByEmail(string email)
        {
            var userProfiles = _userRepository.Get(u => string.Compare(u.Email.Trim(), email.Trim(), StringComparison.InvariantCultureIgnoreCase) == 0).ToList();
            return userProfiles.Select(AutoMapper.Mapper.Map<EntityFW.Entity.UserProfile, UserProfileDTO>).ToList();
        }

        public UserProfileDTO GetByUserId(int userId)
        {
            using (var context = new ExamOnlineDbContext())
            {
                return AutoMapper.Mapper.Map<EntityFW.Entity.UserProfile, UserProfileDTO>(context.UserProfiles.Find(userId));
            }
        }

        public IList<UserProfileDTO> SearchUserDtos(SearchCriteria.SearchCriteria searchCriteria, int pageIndex, int pageSize, out int totalCount)
        {
            var result = _executor.Execute(new GetUserProfileDtoBySearchCriteriaDbCommand(searchCriteria, pageSize, pageIndex));
            if (result == null)
            {
                totalCount = 0;
                return new List<UserProfileDTO>();
            }
            totalCount = result.Count;
            return result.Items;
        }

        public MembershipUser GetCurrentUser()
        {
            return Membership.GetUser();
        }
    }
}
